package com.hs.hlw.credit.system.web.controller.api;

import com.hs.hlw.credit.system.business.dto.ResponseDto;
import com.hs.hlw.credit.system.business.dto.SubmissionDto;
import com.hs.hlw.credit.system.business.dto.SubmissionFormDto;
import com.hs.hlw.credit.system.business.dto.UserDto;
import com.hs.hlw.credit.system.business.service.SubmissionService;
import com.hs.hlw.credit.system.common.enumeration.ExcelTypeEnum;
import com.hs.hlw.credit.system.web.util.RequestUtil;
import com.hualongdata.exception.BusinessException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

/**
 * SubmissionController
 * @author zhb
 * @date 2018/11/22
 */
@RestController
@RequestMapping("/api/submission")
public class SubmissionController {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubmissionController.class);
    private @Autowired SubmissionService submissionService;

    @PostMapping(path = "submit")
    @ApiOperation(value = "单个报送", notes = "单个报送")
    public ResponseDto submit(@RequestBody @Valid SubmissionDto.Submit data, HttpServletRequest request) {
        UserDto user = RequestUtil.getUserFromSession(request);
        return submissionService.submit(data, user);
    }

    @PostMapping(path = "saveDraft")
    @ApiOperation(value = "保存草稿", notes = "单个报送")
    public ResponseDto saveDraft(@RequestBody @Valid SubmissionDto.Submit data, HttpServletRequest request) {
        UserDto user = RequestUtil.getUserFromSession(request);
        return submissionService.saveDraft(data, user);
    }

    @PostMapping(path = "batchDeleteDraft")
    @ApiOperation(value = "批量删除草稿", notes = "批量删除草稿")
    public ResponseDto batchDeleteDraft(@RequestBody @Valid SubmissionDto.BatchDeleteDraft data) {
        return submissionService.batchDeleteDraft(data);
    }

    @PostMapping(path = "batchSubmitDraft")
    @ApiOperation(value = "批量提交草稿", notes = "批量提交草稿")
    public ResponseDto batchSubmitDraft(@RequestBody @Valid SubmissionDto.BatchSubmitDraft data, HttpServletRequest request) {
        UserDto user = RequestUtil.getUserFromSession(request);
        return submissionService.batchSubmitDraft(data, user);
    }

    @RequestMapping(value = "batchSubmit", method = RequestMethod.POST)
    @ApiOperation(value = "批量报送", notes = "批量报送")
    public ResponseDto batchSubmit(@RequestParam @ApiParam(value = "表单id", required = true) Integer formId,
                                   @RequestParam(required = false) @ApiParam(value = "批次id") Integer batchId,
                                   @RequestParam("file") @ApiParam(value = "数据文件", required = true) MultipartFile file,
                                   HttpServletRequest request) {
        try {
            UserDto user = RequestUtil.getUserFromSession(request);

            // 获取文件名和文件流
            String fileName = file.getOriginalFilename();
            ExcelTypeEnum excelType = ExcelTypeEnum.getTypeByFileName(fileName);
            if (excelType == null) {
                throw new BusinessException("文件类型不支持");
            }
            FileInputStream fis = (FileInputStream) file.getInputStream();

            // 把文件转成字节数据，方便后面解析和存储
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = fis.read(buff, 0, 1024)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] fileBytes = swapStream.toByteArray();

            return submissionService.batchSubmit(formId, batchId, fileName, fileBytes, user);
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                BusinessException be = (BusinessException) e;
                ResponseDto responseDto = new ResponseDto(1, be.getErrMsg());
                return responseDto;
            } else {
                LOGGER.error("文件上传失败", e);
                ResponseDto responseDto = new ResponseDto(1, "文件上传失败");
                return responseDto;
            }
        }
    }
}